package com.wizz.trade.util;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.support.atomic.RedisAtomicLong;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author fyftless
 * 用于利用redis生成自增序列id
 */
@SuppressWarnings(value = { "unchecked", "rawtypes" })
@Component
public class SeqIdGenerator {

    @Resource
    public RedisTemplate redisTemplate;

    /**
     * 生成自增序列号
     * @param prefix 前缀
     * @return 序号
     */
    public String generateAutoIncreaseSeqId(String prefix, int length) {
        //根据prefix获取自增序列号，要求使用原子操作，保证线程安全
        RedisAtomicLong redisAtomicLong = new RedisAtomicLong(prefix, redisTemplate.getConnectionFactory());
        long seqId = redisAtomicLong.incrementAndGet();
        //设置过期时间
        redisAtomicLong.expire(1, TimeUnit.DAYS);
        //将自增序列号转换为字符串
        String seqIdStr = String.valueOf(seqId);
        //如果长度不够，前面补0
        if (seqIdStr.length() < length) {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < length - seqIdStr.length(); i++) {
                sb.append("0");
            }
            seqIdStr = sb.toString() + seqIdStr;
        }
        //如果长度溢出，则报错
        if (seqIdStr.length() > length) {
            throw new RuntimeException("序列号长度溢出");
        }
        return seqIdStr;
    }
}
